package com.eobard.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.*;

/**
 * @Author: Eobard Gu
 * @Date: 2025-08-01
 * @Description: Python工具类, 默认使用Python3命令运行脚本
 */
@Slf4j
public class PythonUtils {
    //python2解释器
    public static final String PYTHON_EXPLAINER = "python";
    //python3解释器
    public static final String PYTHON3_EXPLAINER = "python3";

    //默认解释器:使用python3
    private static String defaultExplainer = PYTHON3_EXPLAINER;

    //获取脚本的信息并写入到临时文件中
    public static String getScriptPath(String scriptFileName) {
        try (InputStream is = PythonUtils.class.getClassLoader().getResourceAsStream("temp/python/" + scriptFileName)) {
            if (is == null) {
                throw new FileNotFoundException("找不到资源: temp/python/" + scriptFileName);
            }

            // 创建临时文件
            File tempFile = File.createTempFile("py_script_", "_" + scriptFileName);
            //当jvm关闭时就删除临时文件
            tempFile.deleteOnExit();
            log.info("creating temp script file:{}", tempFile.getAbsoluteFile());
            // 写入脚本内容
            try (OutputStream os = new FileOutputStream(tempFile)) {
                is.transferTo(os);
            }
            //获取路径地址
            return tempFile.getAbsolutePath();
        } catch (IOException e) {
            throw new RuntimeException("无法提取脚本文件: " + scriptFileName, e);
        }
    }

    public static void setPythonExplainer(String explainer) {
        defaultExplainer = explainer;
        log.info("using {} to run script", defaultExplainer);
    }

    public static void run(String scriptPath, String... args) {
        if (StrUtil.isBlank(scriptPath)) throw new RuntimeException(scriptPath + "不能为空");
        if (!FileUtil.exist(scriptPath)) throw new RuntimeException(scriptPath + "脚本不存在");
        //TODO:当前修改md5的脚本中只接受两个输入参数,如果未来有其它脚本,可修改下面这行代码
        if (args.length != 2) throw new IllegalArgumentException("必须输入源地址和目标地址");

        // 检查解释器是否存在
        EnvUtils.isPythonAvailable(defaultExplainer);

        //指定python的运行命令、路径、参数名称
        ArrayList<String> command = new ArrayList<>();
        command.add(defaultExplainer);
        command.add(scriptPath);
        if (args != null) {
            command.addAll(Arrays.asList(args));
        }

        ProcessBuilder pb = new ProcessBuilder(command);
        //合并标准输出和错误输出
        pb.redirectErrorStream(true);

        try {
            //运行命令
            Process process = pb.start();
            //读取python的运行结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                log.info("{}", line);
            }
            //为0表示成功执行脚本
            int exitCode = process.waitFor();
            reader.close();
            if (exitCode != 0) throw new RuntimeException("脚本执行失败");
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e.getMessage());
        }
    }


}
